package com.kgc.rb.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.kgc.rb.common.exception.CommonException;
import com.kgc.rb.common.kafka.KafkaTools;
import com.kgc.rb.common.tools.EmptyUtils;
import com.kgc.rb.common.tools.PrintTools;
import com.kgc.rb.dto.RbResult;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ExceptionInterceptor implements HandlerInterceptor {

    @Autowired
    private KafkaTools kafkaTools;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置响应头解决跨域问题
        response.setHeader("Access-Control-Allow-Origin", "*");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("进入了ExceptionInterceptor拦截器。。。。。。。。。。。。");
        if (EmptyUtils.isNotEmpty(ex)) {//表示控制器中的方法发生了异常
            response.setContentType("text/html;charset=UTF-8");
       //   kafkaTools.sendErrorMessage(ex);//将错误信息，写到Kafka中去
            PrintTools printTools = new PrintTools(response);
            RbResult rbResult = RbResult.build(CommonException.SYSTEM_EXCEPTION.getCode(),
                    CommonException.SYSTEM_EXCEPTION.getMessage());
            printTools.print(JSONObject.toJSON(rbResult));
//            printTools.print(ex);
        }
    }
}
